﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using WeatheRx.Data;

namespace WeatheRx.Managers
{
    public interface IUnitManager
    {
        Unit Get(int unitId);

        void Store(Unit unit);
    }

    public class UnitManager
    {
        public Unit Get(int unitId)
        {
            Unit result;
            using (var db = new HWAPEntities())
            {
                result = db.Units.FirstOrDefault(x => x.UnitId == unitId);
            }
            return result;
        }

        public void Store(Unit unit)
        {
            if (unit.UnitId > 0) Update(unit);
            else Add(unit);
        }

        private void Update(Unit unit)
        {
            using (var db = new HWAPEntities())
            {
                var firstOrDefault = db.Units.FirstOrDefault(x => x.UnitId == unit.UnitId);
                if (firstOrDefault != null)
                    Mapper.Map(unit, firstOrDefault);
                else
                {
                    Add(unit);
                }
                db.SaveChanges();
            }
        }

        private void Add(Unit unit)
        {
            using (var db = new HWAPEntities())
            {
                db.Units.Add(unit);
                db.SaveChanges();
            }
        }
    }
}